package com.superhelper.printer.task;

import java.nio.charset.Charset;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.superhelper.common.mapper.TakeOutOrderMapper;
import com.superhelper.printer.server.Printer;
import com.superhelper.printer.server.PrinterInfo;
import com.superhelper.printer.util.WriterUtils;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

@Component
@Scope("prototype")
public class PrintTask extends AbstractTaskRunnable {

    @Autowired
    private PrinterInfo printerInfo;

    @Autowired
    private TakeOutOrderMapper orderMapper;

    @Override
    protected int execute() {
        log.info("run start taskId:{},printerInfo:{}", task.getId(), printerInfo);
        int printerId = 1;
        Printer printer = printerInfo.getPrinter(printerId);
        if (printer == null) {
            log.info("can't find printer id:{}, delay {} minutes", printerId, 3);
            return 3;
        }
        if (printer.getStatus() == Printer.STATUS_NOPAPER) {
            log.info("printer no paper id:{},delay {} minutes", printerId, 2);
            return 2;
        }
        ByteBuf msg = buildMsg(task.getObjId());
        if (msg == null) {
            log.info("printer id:{}, data is too big ,ignore");
            return SUCCESS;
        }
        printer.getChannel().writeAndFlush(msg);

        return SUCCESS;
    }

    private ByteBuf buildMsg(String objId) {
        ByteBuf buf = Unpooled.buffer(128);
        buf.writeByte(Integer.parseInt("1E", 16));
        ByteBuf data = buildData(objId);
        int byteNum = (data.readableBytes() + 8);// 8是固定的长度
        if (byteNum > 32768) {
            log.info("data is too big, byte num is :{}", byteNum);
            return null;
        }
        // 字节长度
        buf.writeShort(byteNum);
        // Mod1
        buf.writeByte(2);
        // Mod2
        buf.writeByte(0);
        // FLAG
        buf.writeByte(-1);// Integer.parseInt("FF", 16)

        // CMD
        buf.writeByte(Integer.parseInt("50", 16));

        // 数据
        buf.writeBytes(data);

        int sum = WriterUtils.checkSum(buf.copy());
        System.out.println("sum = " + sum);
        // chsum
        buf.writeByte(sum);

        return buf;
    }

    private final static int /* 立即打印 */ PRINT = 10, /* 居左 */LEFT = 1794304,
            /* 居中 */CENTER = 1794305, /* 居右 */RIGHT = 1794306, /* 正常字符 */CHAR_NORMAL = 1777920,
            /* 字符水平放大 */CHAR_HORIZON_BIG = 1777952, /* 字符纵向放大 */CHAR_VERTICAL_BIG = 1777936,
            /* 字符任何方向都放大 */CHAR_BIG = 1777968, /* 正常变粗 */CHAR_BOLD = 1787137,
            /* 正常不加粗 */CHAR_NOT_BOLD = 1787136;
    private final static int/* 语音命令部分 */ AUDIO1 = 7001, AUDIO2 = 16725;

    private ByteBuf buildData(String objId) {
        ByteBuf buf = Unpooled.buffer(256);
        // 订单序列号
        buf.writeShort(888);
        // 订单语音 1号语音
        buf.writeShort(AUDIO1);
        buf.writeShort(AUDIO2);
        buf.writeByte(1);
        // 打两个空白行
        buf.writeByte(PRINT);
        buf.writeByte(PRINT);
        // “饿了么外卖” 居中，而且放大
        buf.writeInt(CENTER);
        buf.writeInt(CHAR_BIG);
        buf.writeBytes("饿了么外卖".getBytes(Charset.forName("GBK")));
        buf.writeByte(PRINT);
        // 接下来的内容靠左，正常字符
        buf.writeInt(LEFT);
        buf.writeInt(CHAR_NORMAL);
        buf.writeBytes("下单时间：2017年10月20日 14：00".getBytes(Charset.forName("GBK")));
        buf.writeByte(PRINT);
        buf.writeBytes("在线支付（已支付）".getBytes(Charset.forName("GBK")));
        buf.writeByte(PRINT);
        buf.writeBytes("订单序号：888".getBytes(Charset.forName("GBK")));
        buf.writeByte(PRINT);
        buf.writeByte(PRINT);
        buf.writeBytes("--------------------------".getBytes(Charset.forName("GBK")));
        buf.writeByte(PRINT);
        buf.writeBytes("菜名      数量  金额".getBytes(Charset.forName("GBK")));
        buf.writeByte(PRINT);
        buf.writeBytes("白切鸡     1   15".getBytes(Charset.forName("GBK")));
        buf.writeByte(PRINT);
        buf.writeBytes("--------------------------".getBytes(Charset.forName("GBK")));
        buf.writeByte(PRINT);
        // 接下来的内容靠右，放大
        buf.writeInt(RIGHT);
        buf.writeInt(CHAR_BIG);
        buf.writeBytes("总金额：15".getBytes(Charset.forName("GBK")));
        buf.writeByte(PRINT);
        // 接下来的内容靠左，正常字符
        buf.writeInt(LEFT);
        buf.writeInt(CHAR_NORMAL);
        buf.writeBytes("送货地址：华南师范大学中山大道西55号研究生公寓b632".getBytes(Charset.forName("GBK")));
        buf.writeByte(PRINT);
        buf.writeBytes("联系人：张晓晓".getBytes(Charset.forName("GBK")));
        buf.writeByte(PRINT);
        buf.writeBytes("联系电话：13800138000".getBytes(Charset.forName("GBK")));
        buf.writeByte(PRINT);
        buf.writeByte(PRINT);
        buf.writeByte(PRINT);

        return buf;
    }

    public static void main(String[] args) {
        // UnsignedBytes.parseUnsignedByte("FF", 16);
        // System.out.println(UnsignedBytes.parseUnsignedByte("FF", 16));
        // for (byte b : bytes) {
        System.out.println(Integer.toBinaryString(34803));
    }
}
